<?php

namespace Home\Controller;


/**
 * 代理团队控制器
 *
 */
class TeamController extends HomeController
{
    /**
     * 获取团队推广二维码url
     */
    public function getQrcodeUrl(){
        $info = M('ptyh')->where(['uid' => $this->uid])->find();

        if(($info['child_hb_rate']*100 < 1)  && ($info['child_xy_rate']*100) < 1){
            $this->showError('请先去 个人中心-推广费率界面设置费率即可获取二维码');
        }
        $url = "http://hbxyk.hihaoge.me/home/user/mregister?tg_num=".$info['tg_num'];
        $url= urlencode($url);
        $this->showSuccess('',$url);
    }

    /**
     * 代理团队列表
     */
    public function index(){
        // 团队-------------------
        $where2 = array();
        $str = I('get.name');
        $status = I('get.status');
        $uid = $this->uid;
        if (!empty($str)) {
            $p = 3;
//            $where2['yh_uid'] = $str;
            $where2['_string'] = ' (yh_uid like "%'.$str.'%")  OR ( name like "%'.$str.'%")';
        }

        if(!empty($status)){
            if($status != 9){
                $where2['status'] = $status;
            }

        }

//        $where2['status'] = 1;
        $where2['pid'] = $uid;
        $team_list = D('Ptyh')->where($where2)->order('uid desc')->select();

        $grandsonCount = 0;

        $grandsonList = array();
        foreach($team_list as $k => $v){

//            $totalsql = "SELECT count(*) FROM jd_ptyh AS p WHERE p.path LIKE '{$v['path']}' || '%' ";
//            $totalCount = M('ptyh')->query($totalsql);
            $totalCount = \Home\Logic\UserLogic::getChildCount($v['path'],0);

            $zhijieCount= M('ptyh')->where('pid='.$v['uid'])->count();
            $team_list[$k]['zhijieCount'] = $zhijieCount;
            $team_list[$k]['jianjieCount'] = $totalCount - $zhijieCount;
            $team_list[$k]['childCount'] = $totalCount;


            $today = strtotime(date("Ymd"));
            $tomorrow = strtotime(date("Ymd")) + 86400;
            $condition['pay_time'] = array('between',array($today,$tomorrow));
            $condition['uid'] = $v['uid'];
            $condition['status'] = 1;
            //今日订单
            $team_list[$k]['todayOrder'] = M('dingdan')->where($condition)->count();
//            $this->showSuccess('todayorder',M('dingdan')->getLastSql());
            //头像
//            $team_list[$k]['avatar'] = M('member')->where(array('uid' => $v['wx_uid']))->getField('headimgurl');

            $grandsonCount += intval($team_list[$k]['childCount']);

            //三级成员列表
            $where2['pid'] = $v['uid'];
            $grandson = M('Ptyh')->where($where2)->order('uid desc')->select();

            $grandsonList = $grandson;
        }



        foreach($grandsonList as $k => $v){
            $grandsonList[$k]['childCount'] = M('ptyh')->where('pid='.$v['uid'])->count();//代理数量
            $today = strtotime(date('Y-m-d'));
            $tomorrow = strtotime(date('Y-m-d'),strtotime('+1 day'));
            $condition['pay_time'] = array('in',array($today,$tomorrow));
            //今日订单
            $grandsonList[$k]['todayOrder'] = M('dingdan')->where($condition)->count();
//            $grandsonCount += intval($grandsonList[$k]['childCount']);
            //头像
            $grandsonList[$k]['avatar'] = M('member')->where(array('uid' => $v['wx_uid']))->getField('headimgurl');

        }

//        foreach($grandsonList as $k => $v){
//
//            array_push($team_list,$v);
//        }
        $_this = D('Ptyh')->where("uid=$uid")->find();
        //直接推广人数
        $childCount = M('ptyh')->where('pid='.$uid)->count();
        $_this['childCount'] = $childCount;
        $_this['grandsonCount'] = $grandsonCount;

        $this_pid = $_this['pid'];
        if ($this_pid == 0 || $this_pid == 1) {
            $pid = 0;   //没有上级或者就是老用户
        } else {
            // 新用户  有上级
            $pid = D('Ptyh')->where("uid=$this_pid")->find();
        }
        $gg_this = D('Gather')->where("uid=$uid")->find();

        if(is_null($team_list)){
            $team_list = array();
        }

        $all = \Home\Logic\UserLogic::getChildCount($_this['path'],0);
        $zhi = \Home\Logic\UserLogic::getChildCount($_this['path'],1);
        $jian = $all - $zhi;
        $data = [
//            'parentdata' => $pid, //上级用户数据
            'selfdata' => $_this, //当前用户,
//            'gatherdata' => $gg_this, //分销数据
            'teamlist' => $team_list, //团队列表
            'totalZhijie' => $zhi,
            'totalJianjie' => $jian
        ];
        $this->showSuccess('',$data);
    }

    /**
     * 调整下级费率
     */
    public function setChildRate(){
        $uid = I('post.child_uid'); //下级用户id
        $up_set = I('post.up_set'); //花呗
        $up_set2 = I('post.up_set2'); //信用卡

        if(empty($uid) || empty($up_set) || empty($up_set2)){
            $this->showError('参数不能为空');

        }

        //自身
        $_this = D('Gather')->where(['uid' => $this->uid])->find();
        $up_set = (float)$up_set;
        $up_set2 = (float)$up_set2;

        //下级
        $child = D('Gather')->where(['uid' => $uid])->find();
//        dump($up_set*100);dump($child['up_set']*100);dump('xyk: '.$child['up_set2']);dump($up_set*100 > $child['up_set']*100);exit;

        if($up_set*100 > $child['up_set']*100){
            $this->showError('花呗只可下调',['upset' => $up_set, 'child' => $child['up_set']]);
        }
        if ($up_set*100 >= ($_this['up_set']*100+5)) {
            if ($up_set*100 <= ($_this['up_set']*100 + 50)) {


                $data['up_set'] = $up_set;
            } else {

                $this->showError('设置的花呗费率范围不可高于您费率的0.5%');
            }
        }  else {

//            $this->showError('设置的花呗费率范围不可小于您自身的费率');
            $this->showError('设置的花呗费率范围须大于自身的0.05');
        }


        if($up_set2 && ($up_set2 > $child['up_set2'])){
            $this->showError('信用卡费率只可下调');
        }


        $up_set2_condition = ($up_set2*100 >= ($_this['up_set2']*100+5));

        if (!empty($up_set2) && $up_set2_condition) {
            if ($up_set2 <= ($_this['up_set2'] + 0.2)) {

                $data['up_set2'] = $up_set2;
            } else {

                $this->showError('设置的信用卡费率范围不可高于您费率的0.2%');
            }

        } else if (empty($up_set2)) {

        } else {

            $this->showError('设置的信用卡费率范围须大于自身的0.05');
        }

        $id = D('Gather')->where(['uid' => $uid])->save($data);
        if($id !== false){
            $this->showSuccess('设置成功');
        }else{
            $this->showError('设置失败');
        }

    }

    /**
     * 获取下级费率信息
     */
    public function getChildRate(){
        $uid = I('get.child_uid'); //下级用户id

        $ptyh = M('ptyh')->where(['uid' => $uid])->field('name,alipay')->find();
        $gather = D('Gather')->where(['uid' => $uid])->field('up_set,up_set2')->find();
        $this->showSuccess('',[
            'name' => $ptyh['name'],
            'alipay' => $ptyh['alipay'],
            'up_set' => $gather['up_set'],
            'up_set2' => $gather['up_set2']

        ]);


    }


    /**
     * 下级代理订单
     */
    public function childOrder(){

        $child_uid = I('get.child_uid');
        $type = I('type'); //0=订单，1=分润
        $today = strtotime(date("Ymd"));
        $tomorrow = strtotime(date("Ymd")) + 86400;
        $condition['pay_time'] = array('between',array($today,$tomorrow));
        $condition['uid'] = $child_uid;
        $condition['status'] = 1;
        //今日订单
        $todayOrder = M('dingdan')->where($condition)->count();
        $todayFenrun = M('Dividend')->where(['parent' => $this->uid])->sum('divide');
        is_null($todayFenrun) ? $todayFenrun = 0.00 : $todayFenrun;

        $ptyh = M('ptyh')->find($child_uid);
//        $avatar = M('member')->where(array('uid' => $ptyh['wx_uid']))->getField('headimgurl');

        $userInfo = [
            'name' => $ptyh['name'],
            'avatar' => $ptyh['avatar']
        ];


        $orderList = [];

        if($type == 1){
            $list =  M('dividend')->where(['uid' => $child_uid])->limit(30)->select();
//            dump(M('dividend')->getLastSql());exit;
            foreach($list as $k => $v){
                $orderList[$k]['danhao'] = $v['danhao'];
                $orderList[$k]['time'] = $v['time'];
                $orderList[$k]['account'] = $v['divide'];
            }

        }else{
            $list =  M('dingdan')->where(['uid' => $child_uid])->limit(30)->select();
//            dump(M('dingdan')->getLastSql());exit;
            foreach($list as $k => $v){
                $orderList[$k]['danhao'] = $v['danhao'];
                $orderList[$k]['time'] = $v['pay_time'];
                $orderList[$k]['account'] = $v['pay_money'];
            }
        }

        $this->showSuccess('',['userInfo' => $userInfo,'todayOrder' => $todayOrder, 'todayFenrun' => $todayFenrun, 'list' => $orderList]);

    }


    /**
     *团队排行榜
     */
    public function teamRankList(){
        $selfOrderCount = M('dingdan')->where(['uid' => $this->uid,'status' => 1])->count();
        $child = M('ptyh')->where(['pid' => $this->uid,'status' => 1])->select();
        $childOrderCount = 0;
        $grandOrderCount = 0;
        foreach($child as $k => $v){
            $childOrderCount += M('dingdan')->where(['uid' => $v['uid'],'status' => 1])->count();

            $grand = M('ptyh')->where(['uid' => $v['uid'],'status' => 1])->select();
            foreach($grand as $ko => $vo){
                $grandOrderCount += M('dingdan')->where(['uid' => $vo['uid'],'status' => 1])->count();
            }
        }

        $teamOrderCount = intval($selfOrderCount) + $childOrderCount + $grandOrderCount;
        $client = new \Predis\Client(C('REDIS'));
        $key = "alishouyinTeamOrderList";
        $ptyh = M('ptyh')->where(['uid' => $this->uid])->find();
        $client->zadd($key,intval($teamOrderCount),$ptyh['name']);
        $list = $client->zrevrange($key,0,10,'withscores');

        $data = [];
        foreach($list as $k => $v){
           $data[] = [
               'name' => $k,
               'score' => $v
           ];
        }

        $this->showSuccess('',$data);
    }

    /**
     * 排行榜规则
     */
    public function teamRankRule(){
        $info = M('page')->where(['category_id' => 14])->find();
        $this->showSuccess('',$info);
    }

    public function pageindex(){
        //排行榜
        $ranklist = M('ptyh')->field('uid,name,account,phone,tuiguang_num')->order('tuiguang_num desc')->limit(100)->select();
        //本月月初时间戳
        $month_start=mktime(0, 0 , 0,date("m"),1,date("Y"));

        $today = strtotime( date("Y-m-d") ); //今天
        $map['pay_time'] = array( array('EGT',$month_start),array('ELT',$today) );

        foreach($ranklist as $k => $v){
            $map['uid'] = $v['uid'];
            $map['status'] = 7;//分账成功
            $ranklist[$k]['orderCount'] = M('dingdan')->where($map)->count();
        }
        $this->showSuccess('',['ranklist' => $ranklist]);
    }








}